package com.qili.controller.supervisor;

import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qili.base.controller.BaseController;
import com.qili.base.service.BasePathConfigService;
import com.qili.core.utils.DictTypes;
import com.qili.core.utils.DictUtil;
import com.qili.core.utils.FileUtils;
import com.qili.entity.affaircase.dto.AffairCaseDTO;
import com.qili.entity.base.*;
import com.qili.entity.base.dto.BaseStageMileDTO;
import com.qili.entity.supervisor.*;
import com.qili.entity.supervisor.dto.*;
import com.qili.entity.supplier.ProjectPlace;
import com.qili.entity.supplier.ProjectPlaceChange;
import com.qili.entity.supplier.SupplierProject;
import com.qili.entity.supplier.SupplierProjectAccept;
import com.qili.entity.supplier.dto.ProjectPlaceDTO;
import com.qili.entity.sys.SysRegion;
import com.qili.entity.sys.SysUser;
import com.qili.entity.sys.SysUserWorkExperience;
import com.qili.entity.sys.dto.SysUserDTO;
import com.qili.exception.MyException;
import com.qili.service.SysUserService;
import com.qili.service.base.*;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.ProjectPlaceService;
import com.qili.service.supplier.SupplierProjectAcceptService;
import com.qili.service.supplier.SupplierProjectManagerService;
import com.qili.service.sys.RoleUserService;
import com.qili.service.sys.SysRegionService;
import com.qili.service.sys.SysUserWorkExperienceService;
import com.qili.util.*;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;

import static java.util.Objects.isNull;

/**
 * @Author Zhangshuo
 * @date 2020/11/20 18:06
 **/
@Controller
@Slf4j
@RequestMapping("/supervisor/projectManager")
public class CreateProjectController extends BaseController {

    @Autowired
    private SupervisorFileService supervisorFileService;
    @Autowired
    private SupervisorProjectService supervisorProjectService;
    @Autowired
    ProjectContractService projectContractService;
    @Autowired
    ProjectLeaderService projectLeaderService;
    @Autowired
    ProjectUnitConstructionService projectUnitConstructionService;
    @Autowired
    SupervisorProjectStageService supervisorProjectStageService;
    @Autowired
    SupervisorProjectMilepostService supervisorProjectMilepostService;
    @Autowired
    BaseStageService baseStageService;
    @Autowired
    BaseMilepostService baseMilepostService;
    @Autowired
    SysRegionService sysRegionService;
    @Autowired
    BaseDictService baseDictService;
    @Autowired
    BasePathConfigService basePathConfigService;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysUserWorkExperienceService userWorkExperienceService;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    SupervisorProjectPayService supervisorProjectPayService;
    @Autowired
    BaseCompanyService baseCompanyService;
    @Autowired
    ProjectAdminService projectAdminService;
    @Autowired
    ProjectNoticeServie projectNoticeServie;
    @Autowired
    SupervisorProjectModifiedRecordService modifiedRecordService;
    @Autowired
    SupervisorFileTempService supervisorFileTempService;
    @Autowired
    SupplierProjectAcceptService supplierProjectAcceptService;
    @Autowired
    SupplierProjectManagerService supplierProjectManagerService;
    @Autowired
    ProjectPlaceService projectPlaceService;
    @Autowired
    BaseCompanyOwnerService  baseCompanyOwnerService;
    @Autowired
    SupervisorPayRecordService supervisorPayRecordService;


    /**
     * @param model
     * @Author:Zhangshuo
     * @Description:跳转创建项目
     * @Date:17:40 2020/11/25
     */
    @GetMapping(value = "create")
    @RequiresPermissions("sr:create")
    public String create(Model model) {
        /*项目来源*/
        List<BaseDict> projectSourcelist = DictUtil.getDictByType(DictTypes.PROJECT_SOURCE);
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.PROJECT_TYPE);
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        /*是否续签*/
        List<BaseDict> isContinueList = DictUtil.getDictByType(DictTypes.IS_CONTINUE);
        /*行业类型*/
        List<BaseDict> AlstHyType = DictUtil.getDictByType(DictTypes.INDUSTRY);
        /*  付款次数 */
        List<BaseDict> payCountList = DictUtil.getDictByType(DictTypes.PAY_COUNT);
        /*  付款方式*/
        List<BaseDict> payList = DictUtil.getDictByType(DictTypes.PAY);
        /*  付款方式*/
        List<BaseCompany> AlstCompany = baseCompanyService.selectAll();
        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();

        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        //当前用户
        SysUser user = sysUserService.selectByPrimaryKey(CommonUtil.getUserId());
        //获取监理合同额----监理实施细则里程碑显示阈值
        List<BaseDict> supervisorContractQuota = DictUtil.getDictByType(DictTypes.JLHTE);
        model.addAttribute("currId", CommonUtil.getUserId());
        model.addAttribute("user", user);
        model.addAttribute("projectTypeList", projectTypeList);
        model.addAttribute("provincelist", provincelist);
        model.addAttribute("projectSourcelist", projectSourcelist);
        model.addAttribute("checkShapeList", checkShapeList);
        model.addAttribute("isContinueList", isContinueList);
        model.addAttribute("payCountList", payCountList);
        model.addAttribute("hytypelist", AlstHyType);
        model.addAttribute("payList", payList);
        model.addAttribute("comlist", AlstCompany);
        model.addAttribute("comlistOwner", alstCompanyGs);
        model.addAttribute("supervisorContractQuota", supervisorContractQuota.size() > 0 ? supervisorContractQuota.get(0).getBadtLevel1() : "");
        model.addAttribute("jlssxzMilepost", "007");
        model.addAttribute("jlssxzMilepost2", "016");
        // 添加 质保 付款节点查询
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtTypecode("ZHIBAO");
        List<BaseDict> baseDicts = baseDictService.select(baseDict);
        model.addAttribute("zb",baseDicts);
        return "/supervisor/projectManager/create";
    }

    /**
     * @param request
     * @Author:Zhangshuo
     * @Description:修改项目基本信息
     * @Date:9:46 2020-12-12
     */
    @GetMapping(value = "projectInfor")
    public String projectInfor(HttpServletRequest request,Model model) {
        String id = request.getParameter("id");

        // 查询项目
        SupervisorProjectDTO supervisorProjectdto = new SupervisorProjectDTO();
        supervisorProjectdto.setId(id);
        List<SupervisorProjectDTO> projectlist = supervisorProjectService.selectSupervisorProject(supervisorProjectdto);
        if (projectlist.size() > 0) {
            supervisorProjectdto = projectlist.get(0);
        }
        //供需表Id
        String supProjectId = supervisorProjectdto.getSupProjectId();
        if(StringUtil.isNotBlank(supProjectId)){
            SupplierProject project = supplierProjectManagerService.selectByPrimaryKey(supProjectId);
            String contractNo = project.getContractNo();
            String payOrProjectNo = project.getPayOrProjectNo();
            String checkShape = project.getCheckShape();

            if(StringUtil.isNotBlank(contractNo)){
                request.setAttribute("htbh", "0");
            }
            if(StringUtil.isNotBlank(payOrProjectNo)){
                request.setAttribute("cgbh", "0");
            }
            if(StringUtil.isNotBlank(checkShape)){
                request.setAttribute("jlxs", "0");
            }

        }

        /*项目分包*/
        ProjectContractDTO projectContract = new ProjectContractDTO();
        projectContract.setProjectId(id);
        List<ProjectContract> pklist = projectContractService.selectPackge(projectContract);
        /*项目负责人*/
        ProjectLeaderDTO leader = new ProjectLeaderDTO();
        leader.setSupervisorProjectId(id);
        List<ProjectLeaderDTO> listyz = projectLeaderService.selectProjectLeaderList(leader);
        // 承建单位
        ProjectUnitConstructionDTO projectUnitConstruction = new ProjectUnitConstructionDTO();
        projectUnitConstruction.setSupervisorProjectId(id);
        List<ProjectUnitConstructionDTO> listcj = projectUnitConstructionService.selectProjectUnitList(projectUnitConstruction);
        // 查询项目阶段 不包含其他监理工作
        SupervisorProjectStageDTO dto = new SupervisorProjectStageDTO();
        dto.setProjectId(id);
        dto.setNotStageNo("005");
        List<SupervisorProjectStageDTO> listStage = supervisorProjectStageService.selectProjectStage(dto);
        // 查询项目里程
        SupervisorProjectMilepostDTO su = new SupervisorProjectMilepostDTO();
        su.setProjectId(id);
        List<SupervisorProjectMilepostDTO> AlistMilePost = supervisorProjectMilepostService.selectProjectmilepost(su);
        /*项目来源*/
        List<BaseDict> projectSourcelist = DictUtil.getDictByType(DictTypes.PROJECT_SOURCE);
        /*项目类型*/
        List<BaseDict> projectTypeList = DictUtil.getDictByType(DictTypes.PROJECT_TYPE);
        /*监理形式*/
        List<BaseDict> checkShapeList = DictUtil.getDictByType(DictTypes.CHECK_SHAPE);
        /*是否续签*/
        List<BaseDict> isContinueList = DictUtil.getDictByType(DictTypes.IS_CONTINUE);
        /*行业类型*/
        List<BaseDict> AlstHyType = DictUtil.getDictByType(DictTypes.INDUSTRY);
        /*项目归属*/
        List<BaseCompany> AlstCompany = baseCompanyService.selectAll();

        // 项目归属
        List<BaseCompanyOwner> alstCompanyGs = baseCompanyOwnerService.selectAll();
        /*技术负责人*/
        SysUserDTO sysUser = new SysUserDTO();
        sysUser.setCompanyName(supervisorProjectdto.getSupervisorCompany());
        sysUser.setUserRole("jsfzr");
        List<SysUser> Alsttelplist = sysUserService.getUserDicts(sysUser);
        /*总监理工程师*/
        sysUser.setUserRole("zjlgcs");
        List<SysUser> Alstsuerlist = sysUserService.getUserDicts(sysUser);
        /*项目经理*/
        sysUser.setUserRole("xmjl");
        List<SysUser> Alstpmplist = sysUserService.getUserDicts(sysUser);
        // 省
        List<SysRegion> provincelist = sysRegionService.selectListByLevelId("1");
        // 市
        List<SysRegion> citylist = sysRegionService.selectSysRegionByParentCode(supervisorProjectdto.getProvince());
        // 县
        List<SysRegion> countylist = sysRegionService.selectSysRegionByParentCode(supervisorProjectdto.getCity());
        //获取监理合同额----监理实施细则里程碑显示阈值
        List<BaseDict> supervisorContractQuota = DictUtil.getDictByType(DictTypes.JLHTE);
        /*判断当前角色 总监理工程师只能修改 总工期和阶段时长 */
        String zjl = "";
        String superEn = supervisorProjectdto.getSupervisorEngineer();
        if (CommonUtil.getUserId().equals(superEn)) {
            zjl = "true";
        }
        request.setAttribute("zjl", zjl);

        String createrId = supervisorProjectdto.getCreateBy();
        SysUser creater = sysUserService.selectByPrimaryKey(createrId);
        if (creater != null && StringUtils.isNotBlank(creater.getSource()) && "001".equals(creater.getSource())) {
            request.setAttribute("createrzz", "1");
        }
        String xmjl = supervisorProjectdto.getProjectManagerPerson();
        if (CommonUtil.getUserId().equals(xmjl)) {
            request.setAttribute("xmjl", "1");
        } else {
            request.setAttribute("xmjl", "0");
        }
        // 2021 1127 特殊情况     2021 1127  既是项目经理又是总监理  权限并集
        // 获取项目的状态
        if(CommonUtil.getUserId().equals(xmjl)  && CommonUtil.getUserId().equals(superEn) ){
            String status = supervisorProjectdto.getStatus();
            if("001".equals(status)){
                // 项目经理的 权限大
                request.setAttribute("xmjl", "1");
                request.setAttribute("zjl", "");
            }else{
                // 提交之后 总监理的权限大
                request.setAttribute("xmjl", "0");
                request.setAttribute("zjl", "true");
            }
        }






        ProjectPlaceDTO pacedto = new ProjectPlaceDTO();
        pacedto.setSupProjectId(supervisorProjectdto.getId());
        pacedto.setType("001");
        List<ProjectPlaceDTO> listpalce = projectPlaceService.selectPlace(pacedto);
        for (int i = 0; i < listpalce.size(); i++) {
            String province = listpalce.get(i).getProvince();
            List<SysRegion> citylist1 = sysRegionService.selectSysRegionByParentCode(province);
            listpalce.get(i).setCitys(citylist1);
            String city = listpalce.get(i).getCity();
            List<SysRegion> countylist2 = sysRegionService.selectSysRegionByParentCode(city);
            listpalce.get(i).setCountys(countylist2);
        }
        supervisorProjectdto.setProjectPlacedtos(listpalce);
        if(listpalce.size() == 0){
            ProjectPlaceDTO p = new ProjectPlaceDTO();
            listpalce.add(p);
        }
        model.addAttribute("listpalce", listpalce);
        request.setAttribute("prj", supervisorProjectdto);
        request.setAttribute("pklist", pklist);
        request.setAttribute("listyz", listyz);
        request.setAttribute("listcj", listcj);
        request.setAttribute("projectTypeList", projectTypeList);
        request.setAttribute("provincelist", provincelist);
        request.setAttribute("citylist", citylist);
        request.setAttribute("countylist", countylist);
        request.setAttribute("listStage", listStage);
        request.setAttribute("listMilePost", AlistMilePost);
        request.setAttribute("projectSourcelist", projectSourcelist);
        request.setAttribute("checkShapeList", checkShapeList);
        request.setAttribute("isContinueList", isContinueList);
        request.setAttribute("hytypelist", AlstHyType);
        request.setAttribute("comlist", AlstCompany);
        model.addAttribute("comlistOwner", alstCompanyGs);
        request.setAttribute("telplist", Alsttelplist);
        request.setAttribute("suerlist", Alstsuerlist);
        request.setAttribute("pmplist", Alstpmplist);
        request.setAttribute("supervisorContractQuota", supervisorContractQuota.size() > 0 ? supervisorContractQuota.get(0).getBadtLevel1() : "");
        request.setAttribute("jlssxzMilepost", "007");
        request.setAttribute("jlssxzMilepost2", "016");

        // 添加 质保 付款节点查询
        BaseDict baseDict = new BaseDict();
        baseDict.setBadtTypecode("ZHIBAO");
        List<BaseDict> baseDicts = baseDictService.select(baseDict);
        model.addAttribute("zb",baseDicts);

        return "/supervisor/projectManager/projectInfor";
    }

    /**
     * @Param
     * @author: zhangshuo
     * @Date: 11:41 2020/11/13
     * @Description: 创建项目
     */
    @RequestMapping("/createsave")
    @ResponseBody
    public JsonUtil addProcject(SupervisorProjectDTO supervisorProjectDTO) {
        String state = supervisorProjectDTO.getStatus();
        //如果有id过来,说明不是第一次保存或者提交了,先彻底删除一遍旧的数据
        if (StringUtils.isNotBlank(supervisorProjectDTO.getId())) {
            //删除原项目相关数据:
            deleteAllAboutProject(supervisorProjectDTO.getId());
        }
        supervisorProjectDTO.setId(null);

        // 创建项目
        if (supervisorProjectDTO != null) {
            try {
                // 项目表
                SupervisorProject supervisorProject = getSubvisorPrjObject(supervisorProjectDTO);
                /*校验项目名称是否重复*/
                SupervisorProject projectnew = new SupervisorProject();
                projectnew.setProjectName(supervisorProject.getProjectName());
                List<SupervisorProject> selectcount = supervisorProjectService.select(projectnew);
                if(selectcount!=null){
                    if(selectcount.size()>0){
                        String createBy = selectcount.get(0).getCreateBy();
                        SysUser sysUser = sysUserService.selectByPrimaryKey(createBy);
                        String realName = sysUser.getRealName();
                        return JsonUtil.error("创建项目失败:项目名称重复！该项目已经被项目经理"+realName+"创建");
                    }
                }
                // 插入项目主表数据
                boolean AbFlag = supervisorProjectService.insertSelective(supervisorProject) > 0;
                supervisorProjectDTO.setProjectId(supervisorProject.getId());
                if (AbFlag) {
                    // 分包数据
                    savePackage(supervisorProjectDTO);

                    // 项目负责人
                    saveLeader(supervisorProjectDTO);
                    // 承建单位
                    saveCreateUnit(supervisorProjectDTO);
                    // 阶段数据和里程数据
                    saveStage(supervisorProjectDTO, false);
                    // 付款方式
                    savePayWays(supervisorProjectDTO);
                    // 发送消息
                    saveSendNotice(supervisorProject);
                    if("002".equals(state)){
                        // 管理员账号
                        saveAdmin(supervisorProjectDTO);
                        //
                        SupervisorProjectMilepost milepostnew = new SupervisorProjectMilepost();
                        milepostnew.setProjectId(supervisorProjectDTO.getProjectId());
                        List<SupervisorProjectMilepost> milepostcurr = supervisorProjectMilepostService.select(milepostnew);
                        for(int x = 0;x<milepostcurr.size();x++){
                            saveSpecialMilePost(supervisorProjectDTO,milepostcurr.get(x));
                        }
                    }
                    // 保存合同签订地点
                    supervisorProjectService.addPalce(supervisorProjectDTO);



                }
                JsonUtil result = new JsonUtil();
                result.setData(supervisorProject.getId());
                result.setFlag(true);
                result.setMsg("创建项目成功");
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("创建项目失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("用户验证失败！！");
        }
    }

    /**
     * 删除项目相关信息
     *
     * @param id
     */
    public void deleteAllAboutProject(String id) {
        if (StringUtils.isNotBlank(id)) {
            //删除leader:
            ProjectLeader delLeader = new ProjectLeader();
            delLeader.setSupervisorProjectId(id);
            projectLeaderService.delete(delLeader);
            //删除admin
            ProjectAdmin admin = new ProjectAdmin();
            admin.setSpId(id);
            projectAdminService.delete(admin);
            //删除package:
            ProjectContract contract = new ProjectContract();
            contract.setProjectId(id);
            projectContractService.delete(contract);
            //删除units:
            ProjectUnitConstruction construction = new ProjectUnitConstruction();
            construction.setSupervisorProjectId(id);
            projectUnitConstructionService.delete(construction);
            //删除阶段:
            SupervisorProjectStage stage = new SupervisorProjectStage();
            stage.setProjectId(id);
            supervisorProjectStageService.delete(stage);
            //删除里程
            SupervisorProjectMilepost milepost = new SupervisorProjectMilepost();
            milepost.setProjectId(id);
            supervisorProjectMilepostService.delete(milepost);
            //删除pay:
            SupervisorProjectPay pay = new SupervisorProjectPay();
            pay.setSppPrjid(id);
            supervisorProjectPayService.delete(pay);
            //删除file:
            SupervisorFile projectFile = new SupervisorFile();
            projectFile.setProjectId(id);
            List<SupervisorFile> select = supervisorFileService.select(projectFile);
            for (SupervisorFile file : select) {
                String url = file.getUrl();
                if (StringUtils.isNotBlank(url)) {
                    File delFile = new File(url);
                    delFile.delete();
                }
            }
            supervisorFileService.delete(projectFile);
            supervisorProjectService.deleteByPrimaryKey(id);
        } else {
            //跑路了
        }
    }

    /**
     * @Param
     * @author: zhangshuo
     * @Date: 11:41 2020/11/13
     * @Description: 修改项目基本信息
     */
    @RequestMapping("/createupdate")
    @ResponseBody
    public JsonUtil saveProcject(SupervisorProjectDTO supervisorProjectDTO) {
        String state = supervisorProjectDTO.getStatus();
        // 创建项目
        if (supervisorProjectDTO != null) {
            try {

                //获取老值
                SupervisorProjectDTO oldProjectInfo = new SupervisorProjectDTO();
                oldProjectInfo.setId(supervisorProjectDTO.getId());
                oldProjectInfo = supervisorProjectService.getOldProjectInfo(oldProjectInfo);
                //比较并修改记录留痕
                if(!(oldProjectInfo.getStatus() == null || "001".equals(oldProjectInfo.getStatus()))){
                    supervisorProjectService.updateCompareProject(oldProjectInfo, supervisorProjectDTO, CommonUtil.getUserId());
                }
                if (!"002".equals(supervisorProjectDTO.getStatus())) {
                    supervisorProjectDTO.setStatus(oldProjectInfo.getStatus());
                }
                // 项目表
                SupervisorProject supervisorProject = new SupervisorProject();
                BeanUtil.copyNotNullBean(supervisorProjectDTO, supervisorProject);
                supervisorProject.setProjectName(supervisorProject.getProjectName().trim());
                supervisorProjectDTO.setProjectName(supervisorProject.getProjectName().trim());
                String status = supervisorProjectDTO.getStatus();
                if ("002".equals(status)) {
                    //记录提交时间
                    supervisorProject.setCommitBy(CommonUtil.getUserId());
                    supervisorProject.setCommitDate(DateUtil.getCurrentDateString());
                }
                /*校验项目名称是重复*/
                Example e = new Example(SupervisorProject.class);
                Example.Criteria c = e.createCriteria();
                c.andNotEqualTo("id", supervisorProjectDTO.getId());
                c.andEqualTo("projectName", supervisorProjectDTO.getProjectName());
                List<SupervisorProject> selectcount = supervisorProjectService.selectByExample(e);
                if(selectcount!=null){
                    if(selectcount.size()>0){
                        String createBy = selectcount.get(0).getCreateBy();
                        SysUser sysUser = sysUserService.selectByPrimaryKey(createBy);
                        String realName = sysUser.getRealName();
                        return JsonUtil.error("创建项目失败:项目名称重复！该项目已经被项目经理"+realName+"创建");
                    }
                }
                // 插入项目主表数据
                boolean AbFlag = supervisorProjectService.updateByPrimaryKeySelective(supervisorProject) > 0;
                supervisorProjectDTO.setProjectId(supervisorProject.getId());
                if (AbFlag) {
                    // 分包数据
                    savePackage(supervisorProjectDTO);
                    // 项目负责人
                    saveLeader(supervisorProjectDTO);
                    // 承建单位
                    saveCreateUnit(supervisorProjectDTO);
                    // 阶段数据和里程数据
                    saveStage(supervisorProjectDTO, true);
                    // 付款方式
                    savePayWays(supervisorProjectDTO);
                    supervisorProjectService.resetProgress(supervisorProjectDTO.getProjectId());
                    //保存 地点
                    ProjectPlace placeDTO = new ProjectPlace();
                    placeDTO.setSupProjectId(supervisorProjectDTO.getId());
                    placeDTO.setType("001");
                    projectPlaceService.delete(placeDTO);
                    //（2） 保存合同签订地点
                    supervisorProjectService.addPalce(supervisorProjectDTO);
                }
                if("002".equals(state)){
                    saveAdmin(supervisorProjectDTO);
                    SupervisorProjectMilepost milepostnew = new SupervisorProjectMilepost();
                    milepostnew.setProjectId(supervisorProjectDTO.getProjectId());
                    List<SupervisorProjectMilepost> milepostcurr = supervisorProjectMilepostService.select(milepostnew);
                    for(int x = 0;x<milepostcurr.size();x++){
                        saveSpecialMilePost(supervisorProjectDTO,milepostcurr.get(x));
                    }
                }
                if("002".equals(state)){
                    JsonUtil ss = JsonUtil.sucess("提交项目成功");
                    return ss ;
                }else{
                    JsonUtil ss = JsonUtil.sucess("修改项目成功");
                    return ss ;
                }


            } catch (Exception e) {
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return JsonUtil.error("修改项目失败:" + e.getMessage());
            }
        } else {
            return JsonUtil.error("用户验证失败！！");
        }
    }


    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description:付款方式
     * @Date:16:39 2020-12-11
     */
    public void savePayWays(SupervisorProjectDTO supervisorProjectDTO) {
        List<SupervisorProjectPayDTO> AlstPayWays = supervisorProjectDTO.getPayList();
        if (!isNull(AlstPayWays)) {
            String AsPrjId = supervisorProjectDTO.getProjectId();
            for (SupervisorProjectPayDTO item : AlstPayWays) {
                if (!isNull(item)) {
                    SupervisorProjectPay supervisorProjectPay = new SupervisorProjectPay();
                    BeanUtil.copyNotNullBean(item, supervisorProjectPay);
                    supervisorProjectPay.setSppPrjid(AsPrjId);
                    String AsId = supervisorProjectPay.getSppId();
                    if (StringUtils.isNotBlank(supervisorProjectPay.getSppNo())) {
                        if (StringUtil.isNotBlank(AsId)) {
                            //页面删除标志
                            String AsDelFlag = supervisorProjectPay.getSppNote();
                            if (StringUtil.isNotBlank(AsDelFlag) && ("-1".equals(AsDelFlag))) {
                                //删除
                                supervisorProjectPayService.deleteByPrimaryKey(AsId);
                            } else {
                                //修改
                                String persent = supervisorProjectPay.getSppPersent();
                                if (StringUtil.isNotBlank(persent)) {
                                    if (persent.indexOf("%") < 0) {
                                        supervisorProjectPay.setSppPersent(persent + "%");
                                    }
                                }
                                supervisorProjectPayService.updateByPrimaryKeySelective(supervisorProjectPay);
                            }
                        } else {
                            //新增
                            supervisorProjectPay.setSppId(null);
                            String persent = supervisorProjectPay.getSppPersent();
                            if (StringUtil.isNotBlank(persent)) {
                                if (persent.indexOf("%") < 0) {
                                    supervisorProjectPay.setSppPersent(persent + "%");
                                }
                            }
                            String AsDelFlag = supervisorProjectPay.getSppNote();
                            if(!"-1".equals(AsDelFlag)){
                                supervisorProjectPayService.insertSelective(supervisorProjectPay);
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @Param
     * @author: Zhangshuo
     * @Date: 11:43 2020/11/13
     * @Description: 获取前端传入数据 并塞入SupervisorProject实体类里面
     */
    public SupervisorProject getSubvisorPrjObject(SupervisorProjectDTO supervisorProjectDTO) throws Exception {
        SupervisorProject supervisorProject = new SupervisorProject();
        BeanUtil.copyNotNullBean(supervisorProjectDTO, supervisorProject);
        supervisorProject.setProjectName(supervisorProject.getProjectName().trim());
        supervisorProjectDTO.setProjectName(supervisorProject.getProjectName().trim());
        if (supervisorProject != null) {
            // 项目状态默认001 未启动
            //supervisorProject.setStatus("001");
            // 项目进度默认值是0
            BigDecimal bigDecimal = new BigDecimal(0);
            supervisorProject.setProgress(bigDecimal.toString());
            // 业务类型
            supervisorProject.setYwType("001");
            // 创建项目的创建时间
            supervisorProject.setCreateDate(new Date());
            String status = supervisorProjectDTO.getStatus();
            if ("002".equals(status)) {
                //记录提交时间
                supervisorProject.setCommitBy(CommonUtil.getUserId());
                supervisorProject.setCommitDate(DateUtil.getCurrentDateString());
            }
        }
        return supervisorProject;
    }

    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description:保存分包信息
     * @Date:14:37 2020/11/25
     */
    public void savePackage(SupervisorProjectDTO supervisorProjectDTO) {
        ArrayList<ProjectContract> projectContractList = supervisorProjectDTO.getProjectContracts();
        if (projectContractList != null) {
            int x=projectContractService.selectOrderMax(supervisorProjectDTO.getProjectId());
            for (ProjectContract projectContract1 : projectContractList) {
                if (!isNull(projectContract1)) {
                    // 主表主键id
                    projectContract1.setProjectId(supervisorProjectDTO.getProjectId());
                    String AsPkId = projectContract1.getId();
                    if (StringUtil.isNotBlank(AsPkId)) {
                        //页面删除标志
                        Integer AiDelFlag = projectContract1.getOrderNum();
                        if ((AiDelFlag != null) && (AiDelFlag == -1)) {
                            //删除
                            projectContractService.deleteByPrimaryKey(AsPkId);
                        } else {
                            //修改
                            projectContractService.updateByPrimaryKeySelective(projectContract1);
                        }
                    } else {
                        x++;
                        //新增
                        projectContract1.setId(null);
                        projectContract1.setOrderNum(x);
                        projectContractService.insertSelective(projectContract1);

                    }
                }
            }
        }
    }

    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description:保存项目负责人信息
     * @Date:14:37 2020/11/25
     */
    public void saveLeader(SupervisorProjectDTO supervisorProjectDTO) throws Exception {
        String userId = CommonUtil.getUserId();
        ArrayList<ProjectLeaderDTO> projectLeaderList = supervisorProjectDTO.getProjectLeaders();
        if (projectLeaderList != null) {
            String AsPrjId = supervisorProjectDTO.getProjectId();
            for (ProjectLeaderDTO projectLeader : projectLeaderList) {
                if (!isNull(projectLeader)) {
                    //页面删除标志
                    String AsDelFlag = projectLeader.getCreateBy();
                    projectLeader.setSupervisorProjectId(AsPrjId);

                    String AsPlId = projectLeader.getId();
                    if (StringUtil.isNotBlank(AsPlId)) {
                        if (StringUtil.isNotBlank(AsDelFlag) && ("-1".equals(AsDelFlag))) {
                            //删除
                            projectLeaderService.deleteByPrimaryKey(AsPlId);
                        } else {
                            //修改
                            String AsRealName = projectLeader.getRealName();
                            String AsProjectLeader = projectLeader.getProjectLeader();
                            SysUser sysUser = sysUserService.selectByPrimaryKey(AsProjectLeader);
                            if (isNull(sysUser)) {
                                String owerCompany = supervisorProjectDTO.getOwerCompany();
                                SysUser user = createUserForFZR(projectLeader, owerCompany);
                                projectLeader.setProjectLeader(user.getId());
                            } else {
                                if (!sysUser.getUsername().equals(AsRealName)) {
//                                    sysUserService.deleteByPrimaryKey(AsProjectLeader);
                                    String owerCompany = supervisorProjectDTO.getOwerCompany();
                                    SysUser user = createUserForFZR(projectLeader, owerCompany);
                                    projectLeader.setProjectLeader(user.getId());
                                }
                            }
                            projectLeaderService.updateByPrimaryKeySelective(projectLeader);
                        }
                    } else {
                        //新增
                        // 创建业主单位负责人账号  判断单位的名字是否存在
                        String owerCompany = supervisorProjectDTO.getOwerCompany();
                        SysUser user = createUserForFZR(projectLeader, owerCompany);
                        ProjectLeader leader = new ProjectLeader();
                        BeanUtil.copyNotNullBean(projectLeader, leader);
                        leader.setId(null);
                        leader.setProjectLeader(user.getId());
                        projectLeaderService.insertSelective(leader);
                        if(!"001".equals(supervisorProjectDTO.getStatus())){
                            SupervisorProjectModifiedRecord modifiedRecord = new SupervisorProjectModifiedRecord();
                            modifiedRecord.setSpmrId(IdUtil.simpleUUID());
                            modifiedRecord.setSpFieldName("项目负责人");
                            modifiedRecord.setSpId(leader.getSupervisorProjectId());
                            modifiedRecord.setSpmrModifiedBy(userId);
                            modifiedRecord.setSpmrModifiedTime(DateUtil.getCurrentDateTimeString());
                            modifiedRecord.setSpmrAction("新增");
                            modifiedRecord.setOldValue("");
                            String name = sysUserService.selectByPrimaryKey(leader.getProjectLeader()).getRealName();
                            modifiedRecord.setNewValue("项目负责人:" + name + ",职务:"+leader.getDuty() + ",分包编号:" + leader.getLeaderFbNumber());
                            modifiedRecordService.insertSelective(modifiedRecord);
                        }
                    }
                }
            }
        }
    }


    /**
     * @Author:zhaoyongke
     * @Description: 消息提醒表
     * @Date:19:34 2021/1/17
     */
    public void saveSendNotice(SupervisorProject supervisorProject) {
        ProjectNotice notice = new ProjectNotice();
        notice.setLinkId(supervisorProject.getId());
        notice.setIsView("0");
        notice.setSendTo(supervisorProject.getCreateBy());
        notice.setTitle(supervisorProject.getProjectName() + "甲方乙方账户创建成功");
        notice.setNoticeType("001");//通知类型 账号通知 001  流程进展通知002  服务评价 003
        notice.setApplicantType("001");// 监理
        projectNoticeServie.insertSelective(notice);
    }

    /**
     * 创建管理员账号
     *
     * @param supervisorProjectDTO
     */
    public void saveAdmin(SupervisorProjectDTO supervisorProjectDTO) {
        //业主单位
        String ownCompany = supervisorProjectDTO.getOwerCompany();
        if (StringUtils.isBlank(ownCompany) && !"001".equals(supervisorProjectDTO.getStatus())) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到业主单位名称");
        }
        String province = supervisorProjectDTO.getProvince();
        if (StringUtils.isBlank(province) && !"001".equals(supervisorProjectDTO.getStatus())) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份编码");
        }
        SysRegion sr = new SysRegion();
        sr.setCode(province);
        List<SysRegion> addressList = sysRegionService.select(sr);
        SysRegion provinceRegion = new SysRegion();
        if(!"001".equals(supervisorProjectDTO.getStatus())){
            if (addressList.size() > 0 ) {
                provinceRegion = addressList.get(0);
            } else {
                throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份");
            }
        }else {
            if (addressList.size() > 0 ) {
                provinceRegion = addressList.get(0);
            }else{
                return;
            }
        }
        String newUserName = sysUserService.getNewUserName(provinceRegion.getName());
        newUserName = sysUserService.checkAndHandlerSameNewUserName(newUserName);
        SysUser sysUser = new SysUser();
        sysUser.setUsername(newUserName);
        sysUser.setRealName(ownCompany);
        sysUser.setGxType("002");
        sysUser.setPassword("12345678");
        sysUser.setCompanyName(supervisorProjectDTO.getOwerCompany());
        //设置默认组织
        sysUser.setPersonType("002");
        //设置为自行注册
        sysUser.setSource("003");
        sysUserService.setUserFilePath(sysUser);
        sysUserService.insertSelective(sysUser);
        projectAdminService.insertSelective(ProjectAdmin.builder().spId(supervisorProjectDTO.getProjectId()).uId(sysUser.getId()).build());
        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add("jsdwglry");
        sysUserService.setMenuAndRolesWhenRegist(sysUser, userRoleNameList);
    }
//-------------------------------------------------------------------------------------------------------------------------------------------
    /**
     * 创建管理员账号
     *
     * @param supervisorProjectDTO
     */
    public void saveAdminByBj(SupervisorProjectDTO supervisorProjectDTO,SupervisorProjectDTO oldSupervisorProjectDTO) {
        //业主单位
        String ownCompany = supervisorProjectDTO.getOwerCompany();
        String oldownCompany = oldSupervisorProjectDTO.getOwerCompany();
        if (StringUtils.isBlank(ownCompany) && !"001".equals(supervisorProjectDTO.getStatus())) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到业主单位名称");
        }
        String province = supervisorProjectDTO.getProvince();
        if (StringUtils.isBlank(province) && !"001".equals(supervisorProjectDTO.getStatus())) {
            throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份编码");
        }
        List<SysUserDTO> sysUserDTOS = sysUserService.selectProjectAdmin(oldSupervisorProjectDTO.getProjectId());
        if(("".equals(oldownCompany) || oldownCompany == null)){
            SysRegion sr = new SysRegion();
            sr.setCode(province);
            List<SysRegion> addressList = sysRegionService.select(sr);
            SysRegion provinceRegion = new SysRegion();
            if(!"001".equals(supervisorProjectDTO.getStatus())){
                if (addressList.size() > 0 ) {
                    provinceRegion = addressList.get(0);
                } else {
                    throw new RuntimeException("创建建设单位管理员账号时,没有获取到合同签订地点的省份");
                }
            }else {
                if (addressList.size() > 0 ) {
                    provinceRegion = addressList.get(0);
                }else{
                    return;
                }
            }
            String newUserName = sysUserService.getNewUserName(provinceRegion.getName());
            newUserName = sysUserService.checkAndHandlerSameNewUserName(newUserName);
            SysUser sysUser = new SysUser();
            sysUser.setUsername(newUserName);
            sysUser.setRealName(ownCompany);
            sysUser.setGxType("002");
            sysUser.setPassword("12345678");
            sysUser.setCompanyName(supervisorProjectDTO.getOwerCompany());
            //设置默认组织
            sysUser.setPersonType("002");
            //设置为自行注册
            sysUser.setSource("003");
            sysUserService.setUserFilePath(sysUser);
            sysUserService.insertSelective(sysUser);
            projectAdminService.insertSelective(ProjectAdmin.builder().spId(supervisorProjectDTO.getProjectId()).uId(sysUser.getId()).build());
            List<String> userRoleNameList = new ArrayList<String>();
            userRoleNameList.add("jsdwglry");
            sysUserService.setMenuAndRolesWhenRegist(sysUser, userRoleNameList);
        }else if(!oldownCompany.equals(ownCompany)){
            if(sysUserDTOS!=null){
                if(sysUserDTOS.size()>0){
                    SysUserDTO admin = sysUserDTOS.get(0);
                    SysUser user =  sysUserService.selectByPrimaryKey(admin.getId());
                    user.setRealName(ownCompany);
                    sysUserService.updateByPrimaryKey(user);
                }

            }


        }
    }

    //-------------------------------------------------------------------------------------------------------------------------------------

    /**
     * @param projectLeader
     * @param owerCompany
     * @Description:为负责人创建账号
     * @Author:zhaoyongke
     * @Date:13:21 2020/12/10
     */
    public SysUser createUserForFZR(ProjectLeaderDTO projectLeader, String owerCompany) {
        // 负责人名字
        String AsRealName = projectLeader.getRealName();
        SysUser AoUser = new SysUser();
        AoUser.setUsername(AsRealName);
        AoUser.setCompanyName(owerCompany);

        //设置默认需方
        AoUser.setGxType("002");
        //设置默认组织
        AoUser.setPersonType("002");
        //设置默认业务类型
        AoUser.setYwType("001");
        //设置默认项目创建:002
        AoUser.setSource("002");
/*        if(StringUtils.isNotBlank(projectLeader.getDuty())){
            SysUserWorkExperience nowWork = new SysUserWorkExperience();
            nowWork.setDuty(projectLeader.getDuty());
            AoUser.setNowWork(nowWork);
        }*/
        saveNewUserIdForProjectLeaderAndUnits(AoUser);

        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add("jsdwxmfzr");
        sysUserService.setMenuAndRolesWhenRegist(AoUser, userRoleNameList);
        return AoUser;

    }


    /**
     * 注册新用户,
     * 查找系统中是否存在同名用户
     * 如果存在同名用户,
     * 如果同一个公司中存在同名用户,给user设置id为该同名用户id
     * 如果同名用户不为同一个公司,那么根据规则生成新用户,给user设置新生成的用户id
     *
     * @param user
     * @return
     */
    public void saveNewUserIdForProjectLeaderAndUnits(SysUser user) {
        SysUser sameNameUser = new SysUser();
        sameNameUser.setRealName(user.getUsername());
        //查询同名的用户
        List<SysUser> listuser = sysUserService.select(sameNameUser);
        Integer count = 0;
        if (listuser.size() > 0) {
            //存在相同username的账号
       /*     SysUser realNameUser = new SysUser();
            realNameUser.setRealName(user.getUsername());
            List<SysUser> listuserReal = sysUserService.select(realNameUser);*/
            for (int i = 0; i < listuser.size(); i++) {
                //相同公司 相同姓名
                SysUser dbUser = listuser.get(i);
                String dbCompanyName = dbUser.getCompanyName() + "";
                String dbRealName = dbUser.getRealName() + "";
                if (dbRealName.equals(user.getUsername()) && user.getCompanyName().equals(dbCompanyName)) {
                    // 相同姓名 相同公司
                    user.setId(dbUser.getId());
                    return;
                } else if (dbRealName.equals(user.getUsername()) && !user.getCompanyName().equals(dbCompanyName)) {
                    // 相同姓名不同公司
                    count++;
                } else {
                    //不同姓名 公司相同、不同姓名不同公司
                    count++;
                }
            }
        }
        //生成账号
        SysUser newUser = new SysUser();
        //获取用户名
        String username = getUserName(user, count);
        newUser.setUsername(username);
        newUser.setCompanyName(user.getCompanyName());
        newUser.setPassword("12345678");
        newUser.setRealName(user.getUsername());
        newUser.setGxType(user.getGxType());
        newUser.setYwType(user.getYwType());
        newUser.setPersonType(user.getPersonType());
        newUser.setSource(user.getSource());
        newUser.setCreateDate(DateUtil.getCurrentDateTime());
        sysUserService.setUserFilePath(newUser);
        sysUserService.insertSelective(newUser);

        SysUserWorkExperience nowWork = user.getNowWork();
        if (nowWork != null) {
            sysUserService.setUserFilePath(newUser);
            nowWork.setIfNow("1");
            nowWork.setSuId(newUser.getId());
            userWorkExperienceService.insertSelective(nowWork);
        }

        user.setId(newUser.getId());
        user.setUsername(newUser.getUsername());
        user.setRealName(newUser.getRealName());
    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description: 获取用户名
     * @Date:17:51 2020/12/31
     */
    public String getUserName(SysUser user, int count) {
        String userName = setUserName(user, count);
        int countUser = sysUserService.checkUser(userName);
        if (countUser != 0) {
            count = count + 1;
            userName = setUserName(user, count);
            int countUser1 = sysUserService.checkUser(userName);
            if (countUser1 > 0) {
                userName = getUserName(user, count);
            }
        }
        return userName;
    }

    /**
     * @param user
     * @param count
     * @Author:zhaoyongke
     * @Description:设置用户名
     * @Date:17:51 2020/12/31
     */
    public String setUserName(SysUser user, int count) {
        SysUser newUser = new SysUser();
        if (count > 0) {
            newUser.setUsername(user.getUsername() + "0" + count);
        } else {
            newUser.setUsername(user.getUsername());
        }
        return newUser.getUsername();
    }

    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description:保存城建单位信息
     * @Date:14:37 2020/11/25
     */
    public void saveCreateUnit(SupervisorProjectDTO supervisorProjectDTO) throws Exception {
        String userId = CommonUtil.getUserId();
        ArrayList<ProjectUnitConstructionDTO> projectUnitConstructionList = supervisorProjectDTO.getProjectUnitConstructions();
        if (projectUnitConstructionList != null) {
            String AsPrjId = supervisorProjectDTO.getProjectId();
            for (ProjectUnitConstructionDTO projectUnitConstruction : projectUnitConstructionList) {
                if (!isNull(projectUnitConstruction)) {
                    String fbcode = projectUnitConstruction.getConstructionSubContractNumber();
                    //页面删除标志
                    String AsDelFlag = projectUnitConstruction.getCreateBy();
                    /*if (StringUtil.isBlank(fbcode) && !"001".equals(supervisorProjectDTO.getStatus()) && !"-1".equals(AsDelFlag)) {
                        throw new Exception("承建单位分包编号不能为空");
                    }*/
                    projectUnitConstruction.setSupervisorProjectId(AsPrjId);

                    String AsId = projectUnitConstruction.getId();
                    if (StringUtil.isNotBlank(AsId)) {
                        if (StringUtil.isNotBlank(AsDelFlag) && ("-1".equals(AsDelFlag))) {
                            //删除
                            projectUnitConstructionService.deleteByPrimaryKey(AsId);
                        } else {
                            //修改
                            String AsRealName = projectUnitConstruction.getRealName();
                            String AsProjectManager = projectUnitConstruction.getProjectManager();
                            SysUser sysUser = sysUserService.selectByPrimaryKey(AsProjectManager);
                            if (isNull(sysUser)) {
                                SysUser user = createUserByUnits(projectUnitConstruction);
                                projectUnitConstruction.setProjectManager(user.getId());
                            } else {
                                if (!sysUser.getUsername().equals(AsRealName)) {
//                                    sysUserService.deleteByPrimaryKey(AsProjectManager);
                                    SysUser user = createUserByUnits(projectUnitConstruction);
                                    projectUnitConstruction.setProjectManager(user.getId());
                                }
                            }
                            projectUnitConstructionService.updateByPrimaryKeySelective(projectUnitConstruction);
                        }
                    } else {
                        //新增
                        //创建承建单位账号
                        SysUser user = createUserByUnits(projectUnitConstruction);
                        ProjectUnitConstruction unitConstruction = new ProjectUnitConstruction();
                        BeanUtil.copyNotNullBean(projectUnitConstruction, unitConstruction);
                        unitConstruction.setProjectManager(user.getId());
                        unitConstruction.setId(null);
                        projectUnitConstructionService.insertSelective(unitConstruction);
                        if (StringUtils.isNotBlank(CommonUtil.getUserId()) && StringUtils.isNotBlank(supervisorProjectDTO.getProjectManagerPerson())
                                && CommonUtil.getUserId().equals(supervisorProjectDTO.getProjectManagerPerson())) {
                            sendNoticeAfterAddUnit(supervisorProjectDTO, unitConstruction);
                        }
                        if(!"001".equals(supervisorProjectDTO.getStatus())){
                            SupervisorProjectModifiedRecord modifiedRecord = new SupervisorProjectModifiedRecord();
                            modifiedRecord.setSpmrId(IdUtil.simpleUUID());
                            modifiedRecord.setSpFieldName("承建单位");
                            modifiedRecord.setSpId(unitConstruction.getSupervisorProjectId());
                            modifiedRecord.setSpmrModifiedBy(userId);
                            modifiedRecord.setSpmrModifiedTime(DateUtil.getCurrentDateTimeString());
                            modifiedRecord.setSpmrAction("新增");
                            modifiedRecord.setOldValue("");
                            String name = sysUserService.selectByPrimaryKey(unitConstruction.getProjectManager()).getRealName();
                            modifiedRecord.setNewValue("承建单位:" + unitConstruction.getUnitConstruction() +
                                    ",承建合同名称:"+unitConstruction.getConstructionContract() +
                                    ",项目经理:" + name + ",开始工期时间:" + unitConstruction.getStartPeriod() +
                                    ",结束工期时间:" + unitConstruction.getEndPeriod() + ",承建合同额:" + unitConstruction.getContractAmount() +
                                    ",分包编号:" + unitConstruction.getConstructionSubContractNumber() +
                                    ",合同编号:" + unitConstruction.getContractNo() + ",采购/项目编号:" + unitConstruction.getPayOrProjectNo());
                            modifiedRecordService.insertSelective(modifiedRecord);
                        }
                    }
                }
            }
        }
    }

    public void sendNoticeAfterAddUnit(SupervisorProject project, ProjectUnitConstruction unitConstruction) {
        //项目经理给项目添加承建单位后:
        if (StringUtils.isNotBlank(project.getId())) {
            //1.给创建人发送账号消息
            SupervisorProject sendNotiProject = new SupervisorProject();
            sendNotiProject.setId(project.getId());
            sendNotiProject.setCreateBy(project.getProjectManagerPerson());
            sendNotiProject.setProjectName(project.getProjectName());
            saveSendNotice(sendNotiProject);

            //2.给总监理工程师发送系统消息:    xx项目追加了xx承建单位,请及时查看
            ProjectNotice notice = new ProjectNotice();
            StringBuffer msg = new StringBuffer();
            msg.append(project.getProjectName())
                    .append("项目追加了 ")
                    .append(unitConstruction.getUnitConstruction())
                    .append(" 承建单位,请及时查看");
            notice.setLinkId(project.getId());
            notice.setIsView("0");
            notice.setSendTo(project.getSupervisorEngineer());
            notice.setTitle(msg.toString());
            notice.setNoticeType("004");//通知类型 账号通知 001  流程进展通知002  服务评价 003  页面跳转004
            notice.setApplicantType("001");// 监理
            projectNoticeServie.insertSelective(notice);
        }
    }

    /**
     * @param projectUnitConstruction
     * @Author:Zhangshuo
     * @Description:为承建单位项目经理创建账户
     * @Date:23:58 2020-12-12
     */
    public SysUser createUserByUnits(ProjectUnitConstructionDTO projectUnitConstruction) {
        SysUser user = new SysUser();
        user.setUsername(projectUnitConstruction.getRealName());
        user.setCompanyName(projectUnitConstruction.getUnitConstruction());
        //设置为项目注册
        user.setSource("002");
        // 承建单位为组织 20211026zhoayognke
        user.setPersonType("002");
        //设置角色为需方(承建单位的角色选择是在点击供需系统时提示的完善信息里面完成,这里不设置)
//        user.setGxType("002");
        saveNewUserIdForProjectLeaderAndUnits(user);
        List<String> userRoleNameList = new ArrayList<String>();
        userRoleNameList.add("nupm");
        sysUserService.setMenuAndRolesWhenRegist(user, userRoleNameList);
        return user;
    }

    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description:保存单位信息
     * @Date:14:37 2020/11/25
     */
    public void saveStage(SupervisorProjectDTO supervisorProjectDTO, boolean pModify) throws Exception {
        ArrayList<SupervisorProjectStage> supervisorProjectStageList = supervisorProjectDTO.getSupervisorProjectStages();
        ArrayList<SupervisorProjectMilepost> supervisorProjectMilepostList = supervisorProjectDTO.getSupervisorProjectMileposts();
        if (supervisorProjectStageList != null) {
            String AsPrjId = supervisorProjectDTO.getProjectId();
            SupervisorProjectStage AoSuperPrjStage = supervisorProjectStageList.get(0);
            String AsFlag = AoSuperPrjStage.getCreateBy();
            //修改状态下，而且没有从服务器加载的标记，删除项目原阶段和里程
            if (pModify && (StringUtil.isBlank(AsFlag))) {
                String[] AyPrjIds = new String[]{AsPrjId};
                supervisorProjectStageService.deleteByProjectIds(AyPrjIds);
                supervisorProjectMilepostService.deleteByProjectIds(AyPrjIds);
            }
            for (int i = 0; i < supervisorProjectStageList.size(); i++) {
                AoSuperPrjStage = supervisorProjectStageList.get(i);
                if (!isNull(AoSuperPrjStage)) {
                    AsFlag = AoSuperPrjStage.getCreateBy();
                    AoSuperPrjStage.setCreateBy("");
                    if (StringUtil.isNotBlank(AsFlag) && (AsFlag.equals("-1"))) {

                        //修改
                        if (StringUtils.isNotBlank(AoSuperPrjStage.getStatus())) {
                            //选中的修改,没选中的删除
                            if ("1".equals(AoSuperPrjStage.getStatus())) {
                                supervisorProjectStageService.updateByPrimaryKeySelective(AoSuperPrjStage);
                            } else if ("0".equals(AoSuperPrjStage.getStatus())) {
                                supervisorProjectStageService.deleteByPrimaryKey(AoSuperPrjStage);
                            }
                        }
                        //处理里程的修改
                        for (SupervisorProjectMilepost item : supervisorProjectMilepostList) {
                            String itemStageId = item.getSupervisorProjectStageId();
                            if (!isNull(itemStageId) && (AoSuperPrjStage.getId().equals(itemStageId))) {
                                if (!isNull(item) && StringUtils.isNotBlank(item.getStatus())) {
                                    if ("1".equals(item.getStatus())) {
                                        if("001".equals(item.getMilepostNo()) && !"001".equals(supervisorProjectDTO.getStatus()) ){

                                            SupervisorProjectMilepost milepost = supervisorProjectMilepostService.selectByPrimaryKey(item);
                                            String stepNum_old = milepost.getStepNum();
                                            if(StringUtils.isNotBlank(stepNum_old)){
                                                // 不为空
                                                //2021年6月23日10:03:12 修改:编辑项目基本信息是否续签改变监理招标文件监理投标文件的状态
                                                String[] split = stepNum_old.split(",");
                                                if ("001".equals(supervisorProjectDTO.getIsContinue())) {
                                                    split[0]="12";
                                                    split[1]="22";
                                                    String str = Arrays.toString(split).replace("[", "").replace("]", "").replace(" ", "");
                                                    item.setStepNum(str);
                                                }else{
                                                    item.setStepNum(stepNum_old);
                                                }

                                            }else{
                                                //2021年6月23日10:03:12 修改:编辑项目基本信息是否续签改变监理招标文件监理投标文件的状态
                                                if ("001".equals(supervisorProjectDTO.getIsContinue())) {
                                                    item.setStepNum("12,22,30,40,50,60,70,90");
                                                }else{
                                                    item.setStepNum("10,20,30,40,50,60,70,90");
                                                }

                                            }

                                        }
                                        supervisorProjectMilepostService.updateByPrimaryKeySelective(item);
                                    } else if ("0".equals(item.getStatus())) {
                                        supervisorProjectMilepostService.deleteByPrimaryKey(item);
                                    }
                                }
                            }
                        }
                    } else {
                        if ("1".equals(AoSuperPrjStage.getStatus()) || pModify) {
                            //新增
                            String AsWebStageId = AoSuperPrjStage.getId();
                            String AsStageId = IdUtil.simpleUUID();
                            AoSuperPrjStage.setId(AsStageId);
                            AoSuperPrjStage.setFinishStatus("0");
                            // 主项目id
                            AoSuperPrjStage.setProjectId(AsPrjId);
                            supervisorProjectStageService.insertSelective(AoSuperPrjStage);
                            for (SupervisorProjectMilepost item : supervisorProjectMilepostList) {
                                if (!isNull(item) && ("1".equals(item.getStatus()) || pModify)) {
                                    String AsStateId = item.getSupervisorProjectStageId();
                                    if (StringUtil.isNotBlank(AsStateId)) {
                                        if (AsStateId.equals(AsWebStageId)) {
                                            item.setSupervisorProjectStageId(AsStageId);
                                            saveMeilPost(supervisorProjectDTO, item);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        /*处理其他监理工作阶段*/
        saveOrUpdateQtJlStage(supervisorProjectDTO);
    }

    /**
     * @param supervisorProjectDTO
     * @Author:zhaoyongke
     * @Description:
     * @Date:10:52 2021/1/8
     */
    public void saveOrUpdateQtJlStage(SupervisorProjectDTO supervisorProjectDTO) throws Exception {
        /*查询是否含有其他阶段*/
        SupervisorProjectStage stage = new SupervisorProjectStage();
        stage.setProjectId(supervisorProjectDTO.getProjectId());
        stage.setStageNo("005");
        List<SupervisorProjectStage> stageListqt = supervisorProjectStageService.select(stage);
        /*查询是否有四大阶段*/
        Example e = new Example(SupervisorProjectStage.class);
        Example.Criteria c = e.createCriteria();
        c.andEqualTo("projectId", supervisorProjectDTO.getProjectId());
        c.andNotEqualTo("stageNo", "005");
        int countstage = supervisorProjectStageService.selectCountByExample(e);
        if (stageListqt.size() == 0) {
            if (countstage > 0) {
                /*添加该阶段*/
                String AsStageId = IdUtil.simpleUUID();
                stage.setId(AsStageId);
                stage.setFinishStatus("0");
                // 主项目id
                stage.setProjectId(supervisorProjectDTO.getProjectId());
                SupervisorProjectStageDTO dtoorder = new SupervisorProjectStageDTO();
                dtoorder.setProjectId(supervisorProjectDTO.getProjectId());
                /*查询最大排序*/
                Integer orderNum = supervisorProjectStageService.selectProjectStageMaxOrderNum(dtoorder) + 1;
                stage.setOrderNum(orderNum);
                supervisorProjectStageService.insertSelective(stage);
                // 保存里程
                BaseStage basestage = new BaseStage();
                basestage.setStageNo("005");
                basestage.setProjectTypeNo(supervisorProjectDTO.getProjectType());
                List<BaseStage> listbasestage = baseStageService.select(basestage);
                if (listbasestage.size() > 0) {
                    basestage = listbasestage.get(0);
                }
                String baseStageId = basestage.getId();
                List<BaseMilepost> baselistmilepost = baseMilepostService.selectMilepostListByStageId(baseStageId, DictTypes.PROJECT_MILEPOST.getType());
                for (int i = 0; i < baselistmilepost.size(); i++) {
                    BaseMilepost baseMilepost = baselistmilepost.get(i);
                    SupervisorProjectMilepost milepost = new SupervisorProjectMilepost();
                    String MilepostId = IdUtil.simpleUUID();
                    milepost.setId(MilepostId);
                    milepost.setProjectId(supervisorProjectDTO.getProjectId());
                    milepost.setMilepostNo(baseMilepost.getMilepostNo());
                    milepost.setStatus("1");
                    milepost.setSpmBaseMilePostId(baseMilepost.getId());
                    String enjc = baseMilepost.getMilepostEnjc() + "";
                    if (StringUtil.isBlank(enjc)) {
                        milepost.setPercentage("0");
                    } else {
                        milepost.setPercentage(baseMilepost.getMilepostEnjc());
                    }
                    milepost.setSupervisorProjectStageId(AsStageId);
                    supervisorProjectMilepostService.insertSelective(milepost);
                }

            }

        }
        /*    else{
         *//*修改的时候才可能走这个逻辑*//*
         *//*含有其他监理工作阶段*//*
            if(countstage>0){
                *//*存在四大阶段  不做修改*//*
            }else{
                *//*不存在四大阶段 删除其他监理工作*//*

            }
        }*/
    }

    /**
     * @param supervisorProjectDTO
     * @param supervisorProjectMilepost
     * @Author:Zhangshuo
     * @Description: 保存项目里程
     * @Date:14:37 2020/11/25
     */
    public void saveMeilPost(SupervisorProjectDTO supervisorProjectDTO, SupervisorProjectMilepost supervisorProjectMilepost) throws Exception {
        if (supervisorProjectMilepost != null) {
            // 项目主键
            supervisorProjectMilepost.setProjectId(supervisorProjectDTO.getProjectId());
            // 状态
            supervisorProjectMilepost.setStatus("1");
            // 完成状态
            supervisorProjectMilepost.setFinishStatus("0");
            /*是否续签 001 是 000 否*/
            String isContinue = supervisorProjectDTO.getIsContinue() + "";
            String milepostno = supervisorProjectMilepost.getMilepostNo() + "";
            /*选择是否续签 是 则招标文件里程中  监理招标文件和监理投标文件 默认已完成*/
            if(!"001".equals(supervisorProjectDTO.getStatus())){
                if ("001".equals(milepostno)) {
                    if ("001".equals(isContinue)) {
                        supervisorProjectMilepost.setStepNum("12,22,30,40,50,60,70,90");
                    }
                }
            }
            supervisorProjectMilepostService.insertSelective(supervisorProjectMilepost);
            //特殊处理里程

        }
    }

    /**
     * @param supervisorProjectDTO
     * @Author:Zhangshuo
     * @Description: 里程特殊处理
     * @Date:12:39 2020-12-09
     */
    public void saveSpecialMilePost(SupervisorProjectDTO supervisorProjectDTO,SupervisorProjectMilepost supervisorProjectMilepost) throws Exception {
        String supProjectId = supervisorProjectDTO.getSupProjectId();
            switch (supervisorProjectMilepost.getMilepostNo()) {

                case "001"://招投标文件

                    if (StringUtil.isNotBlank(supProjectId)) {
                        // 招标文件
                        saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "001", ".docx", "1");
                        //投标文件
                        saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "002", ".docx", "2");
                    }

                    break;
                case "002":
                    if (StringUtil.isNotBlank(supProjectId)) {
                        //合同
                        saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "005", ".docx", "9");
                    }
                    break;
                case "012"://处理到货验收中 合同比对报告
                    saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "044", ".docx", "32");
                    break;
                case "011":
                    //检查旁站 检查记录
                    saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "036", ".docx", "20");
                    //旁站记录
                    saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "037", ".docx", "23");
                    break;
                case "033":
                    /*变更处理里程*/
                    //变更统计表
                    saveContractCompare(supervisorProjectDTO, supervisorProjectMilepost, "095", ".docx", "71");
                    break;
                default:
                    break;
            }
    }

    /**
     * @param supervisorProjectDTO
     * @param supervisorProjectMilepost
     * @Author:Zhangshuo
     * @Description:
     * @Date:12:38 2020-12-09
     */
    public void saveContractCompare(SupervisorProjectDTO supervisorProjectDTO, SupervisorProjectMilepost supervisorProjectMilepost, String AsFileType, String AsFileStuffix, String AsFileConfigId) throws Exception{
        String milepost = supervisorProjectMilepost.getMilepostNo();
        String AsTemplateFile = FilePathUtil.getPathConfigTemplateFile(AsFileConfigId);
        if ("001".equals(milepost)) {
            // 查询招标文件
            //上传项目招标文件说明文件  311
            //上传项目招标文件  312
            //上传项目投标文件  313
            //上传合同  314
            //上传合同说明文件  315

            // 招标文件处理
            if ("001".equals(AsFileType)) {
                updateCopyGxZbFile(supervisorProjectDTO,  AsFileConfigId,  supervisorProjectMilepost, AsFileType, AsFileStuffix);
            }else if ("002".equals(AsFileType)){
                // 投标文件
                updateCopyGxTbFile(supervisorProjectDTO, AsFileConfigId, supervisorProjectMilepost, AsFileType, AsFileStuffix);
            }

        } else if ("002".equals(milepost)) {
            //上传合同  314
            //上传合同说明文件  315
            // 合同
            if ("005".equals(AsFileType)) {
                // 合同
                updateCopyGxhTFile(supervisorProjectDTO,  AsFileConfigId, supervisorProjectMilepost, AsFileType, AsFileStuffix);
            }

        } else if ("033".equals(milepost)) {
            /*变更处理*/
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            int AiFile = supervisorFileService.selectCount(supervisorFile);
            if (AiFile == 0) {
                UploadType uploadType = UploadType.getEnumByType(0);
                uploadType.setFilePathId(AsFileConfigId);
                String pNo = "001";
                String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
                uploadType.setFileName(AsFileName);
                List<String> AlstPlaceHolder = new ArrayList<>();
                AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
                uploadType.setPlaceholder(AlstPlaceHolder);
                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                supervisorFile.setUrl(AsFilePath);
                supervisorFile.setFileName(AsFileName);
                supervisorFile.setInd(1);
                supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                try {
                if (FileUtils.CopyFile(AsTemplateFile, AsFilePath)) {
                    supervisorFileService.insertSelective(supervisorFile);
                }
//                else {
//
//                        throw new Exception("复制PathConfig中TemplateFile出现异常");
//                }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        } else {
            /**/
            ArrayList<ProjectContract> projectContractList = supervisorProjectDTO.getProjectContracts();
            if(projectContractList == null){
                return;
            }
            /*获取承建单位*/
            ArrayList<ProjectUnitConstructionDTO> unitConstructionList = supervisorProjectDTO.getProjectUnitConstructions();
            if(unitConstructionList == null){
                return;
            }
            int AiCnt = projectContractList.size();
            /**/
            int k = 0;
            for (int i = 0; i < AiCnt; i++) {

                for (int j = 0; j < unitConstructionList.size(); j++) {
                    /*承建分包编号*/
                    String cjFbCode = unitConstructionList.get(j).getConstructionSubContractNumber();
                    ProjectContract projectContract = projectContractList.get(i);
                    /*分包编号*/
                    String AsFbCode = projectContract.getCode();
                    if (StringUtil.isNotBlank(AsFbCode)) {
                        if (AsFbCode.equals(cjFbCode)) {
                            /*存在承建单位的分包才 生成模板*/
                            SupervisorFile supervisorFile = new SupervisorFile();
                            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
                            supervisorFile.setPcId(projectContract.getId());
                            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
                            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
                            supervisorFile.setType(AsFileType);
                            int AiFileCnt = supervisorFileService.selectCount(supervisorFile);
                            if (AiFileCnt == 0) {
                                UploadType uploadType = UploadType.getEnumByType(0);
                                uploadType.setFilePathId(AsFileConfigId);
                                String pNo = "001";
                                if ("20".equals(AsFileConfigId) || "23".equals(AsFileConfigId)) {
                                    pNo = StringUtil.autoGenericCode((k + 1) + "", 3);
                                }
                                String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, AsFbCode, AsFileStuffix, pNo);
                                uploadType.setFileName(AsFileName);
                                List<String> AlstPlaceHolder = new ArrayList<>();
                                AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
                                AlstPlaceHolder.add(AsFbCode);
                                uploadType.setPlaceholder(AlstPlaceHolder);

                                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                                supervisorFile.setUrl(AsFilePath);
                                supervisorFile.setFileName(AsFileName);
                                supervisorFile.setInd((k + 1));
                                supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                                if (FileUtils.CopyFile(AsTemplateFile, AsFilePath)) {
                                    supervisorFileService.insertSelective(supervisorFile);
                                    if ("20".equals(AsFileConfigId) || "23".equals(AsFileConfigId)) {
                                        //动态更改文件的包号
                                        Map<String, String> bookmarkMap = new HashMap<>();
                                        /*项目名称*/
                                        bookmarkMap.put("PO_F1", supervisorProjectDTO.getProjectName());
                                        /*业主单位*/
                                        bookmarkMap.put("PO_F2", supervisorProjectDTO.getOwerCompany());
                                        String superCompanyId = supervisorProjectDTO.getSupervisorCompany();
                                        BaseCompany baseCompany = baseCompanyService.selectByPrimaryKey(superCompanyId);
                                        if (baseCompany != null) {
                                            /*监理单位*/
                                            bookmarkMap.put("PO_F3", baseCompany.getBcName());
                                        }
                                        /*承建单位*/
                                        bookmarkMap.put("PO_F4", unitConstructionList.get(j).getUnitConstruction());
                                        bookmarkMap.put("PO_C", pNo);
                                        WordUtil.replaceBookmark(AsFilePath, AsFilePath, bookmarkMap);
                                    }
                                } else {
                                    throw new Exception("复制PathConfig中TemplateFile出现异常");
                                }
                            }
                            k++;
                        }
                    }
                }
            }
        }


    }

    public   void updateCopyGxZbFile(SupervisorProjectDTO  supervisorProjectDTO,String AsFileConfigId,SupervisorProjectMilepost supervisorProjectMilepost,String AsFileType,String  AsFileStuffix)  throws  Exception{
        // 供需表Id
        SupervisorFile supervisorFilezb = new SupervisorFile();
        supervisorFilezb.setProjectId(supervisorProjectDTO.getSupProjectId());
        supervisorFilezb.setType("311");//招标文件 说明
        List<SupervisorFile> selectzbgx = supervisorFileService.select(supervisorFilezb);
        int zbnum = 1;
        for (int i = 0; i < selectzbgx.size(); i++) {
            SupervisorFile supervisorFilegx = selectzbgx.get(i);
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);

            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            supervisorFile.setUrl(supervisorFilegx.getUrl());
//            supervisorFile.setFileName(AsFileName);
            supervisorFile.setFileName(AsFileName.replace( "监理招标文件","监理招标文件说明"));
            supervisorFile.setInd(zbnum);
            supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            supervisorFile.setCreateType("1");
           //if (FileUtils.CopyFile(supervisorFilegx.getUrl(), AsFilePath)) {
                supervisorFileService.insertSelective(supervisorFile);
           // } else {
               //throw new Exception("复制文件出现异常");
           // }
            zbnum++;
        }
        SupervisorFile supervisorFileTempHtsm = new SupervisorFile();
        supervisorFileTempHtsm.setProjectId(supervisorProjectDTO.getSupProjectId());
        supervisorFileTempHtsm.setType("312");//招标文件
        List<SupervisorFile> selectzbSm = supervisorFileService.select(supervisorFileTempHtsm);
        for (int i = 0; i < selectzbSm.size(); i++) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            SupervisorFile supervisorFileTemp1 = selectzbSm.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            supervisorFile.setUrl(supervisorFileTemp1.getUrl());
            supervisorFile.setFileName(AsFileName);
            supervisorFile.setInd(zbnum);
            supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            supervisorFile.setCreateType("1");
            //if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                supervisorFileService.insertSelective(supervisorFile);
           // } else {
              //  throw new Exception("复制文件出现异常");
            //}
            zbnum++;
        }
    }
    public   void updateCopyGxTbFile(SupervisorProjectDTO  supervisorProjectDTO,String AsFileConfigId,SupervisorProjectMilepost supervisorProjectMilepost,String AsFileType,String  AsFileStuffix)  throws  Exception{

        SupervisorFile supervisorFileTemp = new SupervisorFile();
        supervisorFileTemp.setProjectId(supervisorProjectDTO.getSupProjectId());
        supervisorFileTemp.setType("313");//投标文件
        List<SupervisorFile> selectzb = supervisorFileService.select(supervisorFileTemp);
        int zbnum = 1;
        for (int i = 0; i < selectzb.size(); i++) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            SupervisorFile supervisorFileTemp1 = selectzb.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            supervisorFile.setUrl(supervisorFileTemp1.getUrl());
            supervisorFile.setFileName(AsFileName);
            supervisorFile.setInd(zbnum);
            supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            supervisorFile.setCreateType("1");
            //if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                supervisorFileService.insertSelective(supervisorFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
        // 查询迎接
        SupplierProject supplierProject = supplierProjectManagerService.selectByPrimaryKey(supervisorProjectDTO.getSupProjectId());
        SupplierProjectAccept accept=new SupplierProjectAccept();
        accept.setSupProjectId(supplierProject.getSupProjectId());
        accept.setAcceptBy(supplierProject.getZbBy());
        List<SupplierProjectAccept> selectAccept = supplierProjectAcceptService.select(accept);
        for (int i = 0; i < selectAccept.size(); i++) {
            SupplierProjectAccept accept1 = selectAccept.get(i);
            SupervisorFile supervisorFileTempaccept = new SupervisorFile();
            supervisorFileTempaccept.setProjectId(accept1.getSupAcceptId());
            supervisorFileTempaccept.setType("301");//投标文件
            List<SupervisorFile> selecttbaccept = supervisorFileService.select(supervisorFileTempaccept);
            for (int j = 0; j <selecttbaccept.size(); j++) {
                SupervisorFile supervisorFile = new SupervisorFile();
                supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
                supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
                supervisorFile.setSpmId(supervisorProjectMilepost.getId());
                supervisorFile.setType(AsFileType);
                SupervisorFile supervisorFileTemp1 = selecttbaccept.get(i);
                UploadType uploadType = UploadType.getEnumByType(0);
                uploadType.setFilePathId(AsFileConfigId);
                String pNo = "00" + zbnum;
                String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
                uploadType.setFileName(AsFileName);
                List<String> AlstPlaceHolder = new ArrayList<>();
                AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
                uploadType.setPlaceholder(AlstPlaceHolder);
                String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
                supervisorFile.setUrl(supervisorFileTemp1.getUrl());
                supervisorFile.setFileName(AsFileName);
                supervisorFile.setInd(zbnum);
                supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
                // 从供需复制而来
                supervisorFile.setCreateType("1");
               // if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                    supervisorFileService.insertSelective(supervisorFile);
               // } else {
                   // throw new Exception("复制文件出现异常");
                //}
                zbnum++;

            }
        }


    }

    public   void updateCopyGxhTFile(SupervisorProjectDTO  supervisorProjectDTO,String AsFileConfigId,SupervisorProjectMilepost supervisorProjectMilepost,String AsFileType,String  AsFileStuffix)  throws  Exception{

        SupervisorFile supervisorFileTemp = new SupervisorFile();
        supervisorFileTemp.setProjectId(supervisorProjectDTO.getSupProjectId());
        supervisorFileTemp.setType("314");
        List<SupervisorFile> selectzb = supervisorFileService.select(supervisorFileTemp);
        int zbnum = 1;
        for (int i = 0; i < selectzb.size(); i++) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            SupervisorFile supervisorFileTemp1 = selectzb.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", ".pdf", pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            supervisorFile.setUrl(supervisorFileTemp1.getUrl());
            supervisorFile.setFileName(AsFileName);
            supervisorFile.setInd(zbnum);
            supervisorFile.setFileType(supervisorFileTemp1.getFileType());
            // 从供需复制而来
            supervisorFile.setCreateType("1");
//            if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                supervisorFileService.insertSelective(supervisorFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
        SupervisorFileTemp supervisorFileTempHtsm = new SupervisorFileTemp();
        supervisorFileTempHtsm.setProjectId(supervisorProjectDTO.getSupProjectId());
        supervisorFileTempHtsm.setType("315");
        List<SupervisorFileTemp> selectzbSm = supervisorFileTempService.select(supervisorFileTempHtsm);
        for (int i = 0; i < selectzbSm.size(); i++) {
            SupervisorFile supervisorFile = new SupervisorFile();
            supervisorFile.setProjectId(supervisorProjectDTO.getProjectId());
            supervisorFile.setStageId(supervisorProjectMilepost.getSupervisorProjectStageId());
            supervisorFile.setSpmId(supervisorProjectMilepost.getId());
            supervisorFile.setType(AsFileType);
            SupervisorFileTemp supervisorFileTemp1 = selectzbSm.get(i);
            UploadType uploadType = UploadType.getEnumByType(0);
            uploadType.setFilePathId(AsFileConfigId);
            String pNo = "00" + zbnum;
            String AsFileName = FileUtils.getFileNameByNo(supervisorProjectDTO.getProjectName(), AsFileType, "", AsFileStuffix, pNo);
            uploadType.setFileName(AsFileName);
            List<String> AlstPlaceHolder = new ArrayList<>();
            AlstPlaceHolder.add(supervisorProjectDTO.getProjectName());
            uploadType.setPlaceholder(AlstPlaceHolder);
            String AsFilePath = FilePathUtil.getFullSavePathAndNameByConfigFileId(uploadType);
            supervisorFile.setUrl(supervisorFileTemp1.getUrl());
            supervisorFile.setFileName(AsFileName.replace( "监理合同","监理合同说明"));
            supervisorFile.setInd(zbnum);
            supervisorFile.setFileType(FilePathUtil.getFileSufiix(AsFileName));
            // 从供需复制而来
            supervisorFile.setCreateType("1");
           // if (FileUtils.CopyFile(supervisorFileTemp1.getUrl(), AsFilePath)) {
                supervisorFileService.insertSelective(supervisorFile);
//            } else {
//                throw new Exception("复制文件出现异常");
//            }
            zbnum++;
        }
    }

    @GetMapping(value = "del")
    public JsonUtil deleteProject(String prjid) {
        //返回
        JsonUtil re = new JsonUtil();
        // 删除ID
        if (StringUtil.isNotBlank(prjid)) {
            try {
                //逻辑删除
                SupervisorProject supervisorProject = new SupervisorProject();
                supervisorProject.setId(prjid);
                supervisorProject.setStatus("000");
                supervisorProjectService.updateByPrimaryKey(supervisorProject);
                re.setFlag(true);
            } catch (Exception e) {
                re.setFlag(false);
                re.setMsg("删除项目失败:" + e);
            }
        } else {
            re.setFlag(false);
            re.setMsg("项目ID不可以为空！！");
        }
        return re;
    }

    /**
     * @Param
     * @author: zhanghuawei
     * @Date: 11:41 2020/11/13
     * @Description: 查询baseStage表
     */
    @RequestMapping(value = "/baseStage")
    @ResponseBody
    public JsonUtil selectBaseStage(String projectTypeNo) {
        JsonUtil jsonUtil = new JsonUtil();
        BaseStageMileDTO baseStageDto = new BaseStageMileDTO();
        if (projectTypeNo != null) {
            baseStageDto.setProjectTypeNo(projectTypeNo);
            List<BaseStageMileDTO> baseStageDtoList = baseStageService.selectStageMileByProjectType(baseStageDto);
            if (baseStageDtoList != null) {
                jsonUtil.setData(baseStageDtoList);
                return jsonUtil;
            }
        }
        return null;
    }

    /**
     * @Param
     * @author: zhanghuawei
     * @Date: 11:42 2020/11/13
     * @Description: 查询里程碑 根据stage的id
     */
    @RequestMapping("queryMilePosts")
    @ResponseBody
    public JsonUtil queryMilePosts(String stageId) {

        JsonUtil jsonUtil = new JsonUtil();
        BaseMilepost baseMilepost = new BaseMilepost();
        if (stageId != null) {
            baseMilepost.setStageId(stageId);
            List<BaseMilepost> baseMilepostList = baseMilepostService.select(baseMilepost);
            if (baseMilepostList != null) {
                jsonUtil.setData(baseMilepostList);
            }
            return jsonUtil;
        } else {
            return null;
        }
    }


    @RequestMapping("/showProjectModRecord")
    public String showProjectModRecord(String pid, Model model) {
        if (StringUtils.isBlank(pid)) {
            model.addAttribute("message", "参数异常");
            return "/error/500";
        }
        model.addAttribute("spId", pid);
        return "/supervisor/projectManager/mod-record";
    }

    @ResponseBody
    @RequestMapping("/gerRecordList")
    public ReType gerRecordList(SupervisorProjectModifiedRecord record, Model model, int page, int limit) {
        List<SupervisorProjectModifiedRecord> tList = null;
        Page<AffairCaseDTO> tPage = PageHelper.startPage(page, limit);
        try {
            tList = modifiedRecordService.selectListByPage(record);
        } catch (MyException e) {
            e.printStackTrace();
        }
        return new ReType(tPage.getTotal(), tList);
    }

    /**
     * @param project
     * @Author:zhaoyongke
     * @Description: 获取公司信息
     * @Date:10:17 2021/3/18
     */
    @GetMapping(value = "getCompany")
    @ResponseBody
    public JsonUtil getCompany(SupervisorProjectDTO project) {
        JsonUtil re = new JsonUtil();
        try {
            List<BaseCompany> AlstCompany = baseCompanyService.selectAll();
            re.setFlag(true);
            re.setData(AlstCompany);
            return re;
        } catch (Exception e) {
            e.printStackTrace();
            re.setFlag(false);
            re.setMsg("获取公司异常！！" + e.getMessage());
            return re;
        }
    }

    /**
     * 判断项目是否存在
     *
     * @param project
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkExit")
    public JsonUtil checkExit(SupervisorProject project) {
        SupervisorProject supervisorProject = null;
        if (project != null && StringUtils.isNotBlank(project.getId())) {
            supervisorProject = supervisorProjectService.selectByPrimaryKey(project);
        }
        JsonUtil result = new JsonUtil();
        result.setFlag(supervisorProject != null);
        result.setData(supervisorProject);
        return result;
    }

    /**
     * 判断项目是否存在
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/deletePay")
    public JsonUtil checkExit(String id,String xmId,String zfMoney) {
        if (StringUtil.isNotBlank(zfMoney)){
            // 更新项目表中的数据
            SupervisorProject supervisorProject = supervisorProjectService.selectByPrimaryKey(xmId);
            if (supervisorProject != null && StringUtil.isNotBlank(supervisorProject.getJlPayMoney())){
                // 减掉当前的数据
                BigDecimal num = new BigDecimal(supervisorProject.getJlPayMoney()).subtract(new BigDecimal(zfMoney));
                // 进行更新
                SupervisorProject ss = new SupervisorProject();
                ss.setId(xmId);
                // 如果num为负数，设置为零
                if (num.compareTo(BigDecimal.ZERO) < 0){
                    ss.setJlPayMoney("0");
                }else {
                    ss.setJlPayMoney(num.toString());
                }

                // 根据id修改支付金额
                supervisorProjectService.updateById(xmId,num.toString());
            }
        }
        supervisorPayRecordService.deleteByPrimaryKey(id);
        JsonUtil result = new JsonUtil();
        result.setFlag(true);
        return result;
    }
}
